//------------------------------------------------------------------------------
//
//   author: 小兵（aosnow@yeah.net）
//   create: 2012-5-29 下午22:36:19
//    class: SoundLoader - 声音媒体加载类
//
//------------------------------------------------------------------------------

package starfire.rpc.loader.elements
{
	import flash.errors.IOError;
	import flash.events.Event;
	import flash.media.Sound;
	import flash.media.SoundLoaderContext;
	import flash.net.URLRequest;
	
	import starfire.rpc.URL;
	import starfire.rpc.loader.LoadMessage;
	import starfire.rpc.loader.LoadState;

	[ExcludeClass]
	public class AudioLoader extends LoaderBase
	{
		protected var sound:Sound;
		protected var context:SoundLoaderContext;

		public function AudioLoader( message:LoadMessage )
		{
			super( message );
		}

		override public function canHandleResource():Boolean
		{
			if( super.message )
			{
				var url:URL = new URL( super.message.url );
				return ( url.path.search( /\.mp3$/i ) != -1 );
			}

			return false;
		}

		override protected function executeLoad( message:LoadMessage ):void
		{
			var urlReq:URLRequest = new URLRequest( message.url );

			// 图片加载初始化
			sound = new Sound();
			toggleLoaderListeners( sound, true );

			context = new SoundLoaderContext;
			context.bufferTime = 3000;
			context.checkPolicyFile = true;

			// 开始加载数据
			try
			{
				updateLoadState( LoadState.LOADING );
				sound.load( urlReq, context );
			}
			catch( ioError:IOError )
			{
				IOErrorHandler( null, ioError.message );
			}
			catch( securityError:SecurityError )
			{
				securityErrorHandler( null, securityError.message );
			}
		}

		override protected function executeUnload( message:LoadMessage ):void
		{
			updateLoadState( LoadState.UNLOADING );
			sound = null;
			context = null;
			updateLoadState( LoadState.UNINITIALIZED );
		}

		override protected function loadCompleteHandler( event:Event ):void
		{
			toggleLoaderListeners( sound, false );

			// 保存声音对象的字节数据，使用时通过 Sound.loadCompressedDataFromByteArray 来加载声音数据
			try
			{
				saveCache( sound );
			}
			catch( e:Error )
			{
				return;
			}

			updateLoadState( LoadState.READY );

			// 执行回调函数
			if( complete is Function )
			{
				complete( sound );
			}
		}
	}
}
